package com.zhonggong.readDatabase;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//这个多线程下载没有使用多连接，而是通过单一的连接将数据库内容导入到内存，然后将内存中的集合分给多个线程来读
//这个下载，要不要考虑它的通用性？
//我想导出到文本文件，但是不行。因为文本文档无法无法定位到写入位置
//所以还要用excel表
public class DownUtil<pk extends Object> {//调用多线程进行下载的类
	
	private List<pk> list = null;
	private String excelName;// 复制出来的文件名
	private int threadNum;// 线程数量
	private int fileSize;// 文件总大小
	private DownThread[] th;
	
	public DownUtil(List<pk> list,String excelName,int threadNum)
	{
		this.list = list;//数据库的资源
		this.excelName = excelName;//文件名
		this.threadNum = threadNum;//线程数
		this.th = new DownThread[threadNum];
	}
	
	//这个方法用来创建一张指定大小的Excel表，用来存储数据表内容
	public void createExcel() throws IOException
	{
		
		String[] li = {"姓名","性别","国籍"};
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet();
		XSSFRow row = sheet.createRow(0);  
		for(int i=0;i<li.length;i++)
		{
			XSSFCell cell = row.createCell(i);
			cell.setCellValue(li[i]);
		}
		try {
		FileOutputStream fo = new FileOutputStream(excelName);//............................................
		wb.write(fo);
		fo.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
		finally {
			wb.close();
		}
	}
	
	//下面这个方法，我直接分配给线程的是一个子集
	public void download() throws IOException, InterruptedException
	{
		createExcel();//创建一个空的excel表
		fileSize = list.size();//获得记录的条数
		
		int partSize = fileSize / threadNum;//最后一个线程分的记录会比较多
		System.out.println(partSize);
		for (int i = 0; i < threadNum; i++) {
			int startPos = i * partSize;
			if(i==(threadNum-1))
			{
				List<pk> partList = list.subList(startPos, fileSize);
				System.out.println(startPos + " " + fileSize);
				th[i] = new DownThread(partList, excelName,fileSize-startPos,startPos+1);
				th[i].start();
				th[i].join();
			}
			else
			{
				List<pk> partList = list.subList(startPos, startPos+partSize);
				System.out.println(startPos + " " + (startPos+partSize));
				th[i] = new DownThread(partList, excelName,partSize,startPos+1);
				th[i].start();
				th[i].join();
			}
		}
	}
}
